package com.aichat.ai_chatbackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.aichat.ai_chatbackend.model.entity.ChatSession;
import com.aichat.ai_chatbackend.model.entity.AiCharacter;
import com.aichat.ai_chatbackend.service.ChatSessionService;
import com.aichat.ai_chatbackend.service.AiCharacterService;
import com.aichat.ai_chatbackend.mapper.ChatSessionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
* @author yuppie
* @description 针对表【chat_session(对话会话表)】的数据库操作Service实现
* @createDate 2025-07-13 14:40:37
*/
@Service
public class ChatSessionServiceImpl extends ServiceImpl<ChatSessionMapper, ChatSession>
    implements ChatSessionService{

    @Autowired
    private AiCharacterService aiCharacterService;

    /**
     * 创建或者获取已有的session
     * @param sessionId
     * @param userId
     * @param characterId
     * @return
     */
    @Override
    public ChatSession getOrCreateSession(String sessionId, Long userId, Long characterId) {
        QueryWrapper<ChatSession> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("session_id", sessionId);
        ChatSession chatSession = this.getOne(queryWrapper);

        if(chatSession == null){
            return createSession(userId,characterId);
        }else{
            return chatSession;
        }
    }

    /**
     * 创建会话管理
     * @param userId 用户ID
     * @param characterId AI角色ID
     * @return 创建的会话
     */
    @Override
    public ChatSession createSession(Long userId, Long characterId){
        ChatSession session = new ChatSession();
        
        // 生成唯一的会话ID
        session.setSessionId(UUID.randomUUID().toString().replace("-", ""));
        session.setUserId(userId);
        session.setAiCharacterId(characterId);
        
        // 获取AI角色信息并设置系统提示词
        if (characterId != null) {
            AiCharacter character = aiCharacterService.getById(characterId);
            if (character != null) {
                session.setSessionName("与" + character.getName() + "的对话");
                session.setSystemPrompt(character.getSystemPrompt());
            } else {
                session.setSessionName("智能对话");
                session.setSystemPrompt("你是一个智能聊天助手，请为用户提供有帮助的回答。");
            }
        } else {
            session.setSessionName("智能对话");
            session.setSystemPrompt("你是一个智能聊天助手，请为用户提供有帮助的回答。");
        }
        
        // 设置会话状态和时间
        session.setSessionStatus(1); // 1-进行中
        session.setStartTime(new Date());
        session.setMessageCount(0);
        session.setCreatedAt(new Date());
        session.setUpdatedAt(new Date());
        
        // 保存到数据库
        this.save(session);
        
        return session;
    }

    /**
     * 获取用户会话列表
     * @param userId 用户ID
     * @return 会话列表
     */
    @Override
    public List<ChatSession> getUserSessions(Long userId){
        QueryWrapper<ChatSession> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                   .orderByDesc("updated_at"); // 按更新时间倒序
        
        return this.list(queryWrapper);
    }

    /**
     * 结束会话
     * @param sessionId 会话ID
     */
    @Override
    public void endSession(String sessionId){
        ChatSession session = this.getById(sessionId);
        if (session != null) {
            session.setSessionStatus(2); // 2-已结束
            session.setEndTime(new Date());
            session.setUpdatedAt(new Date());
            this.updateById(session);
        }
    }

    /**
     * 恢复会话
     * @param sessionId 会话ID
     */
    @Override
    public void resumeSession(String sessionId){
        ChatSession session = this.getById(sessionId);
        if (session != null) {
            session.setSessionStatus(1); // 1-进行中
            session.setEndTime(null);
            session.setUpdatedAt(new Date());
            this.updateById(session);
        }
    }

    /**
     * 获取用户的活跃会话
     * @param userId 用户ID
     * @return 活跃会话列表
     */
    public List<ChatSession> getActiveSessionsByUserId(Long userId) {
        QueryWrapper<ChatSession> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                   .eq("session_status", 1) // 进行中的会话
                   .orderByDesc("updated_at");

        return this.list(queryWrapper);
    }

    /**
     * 根据会话名称查找会话
     * @param userId 用户ID
     * @param sessionName 会话名称
     * @return 会话
     */
    public ChatSession findSessionByName(Long userId, String sessionName) {
        QueryWrapper<ChatSession> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                   .eq("session_name", sessionName)
                   .orderByDesc("updated_at")
                   .last("LIMIT 1");
        
        return this.getOne(queryWrapper);
    }

}




